import os
import sys
import argparse

HOME = os.getenv('HOME')
GIT_CONFIGS = '%s/git/configs' % HOME
FREEDOM_E_SDK = '%s/SiFive-OE/sifive_coreip_E21_AHB_rtl_full_v19_08p2p0_release/freedom-e-sdk' % HOME

#set up RISC_PATH and RISC_OCD_PATH
source_cmd = 'source %s/freedom-e-sdk/setup-toolchain.sh' % GIT_CONFIGS
print(source_cmd)
os.system('. %s/freedom-e-sdk/setup.sh' % GIT_CONFIGS)
#make PROGRAM=hello TARGET=eswin-haps-e21 software
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--program', default='hello', help='specify the program')
parser.add_argument('-t', '--target', default='eswin-haps-e21', help='specify the target')
parser.add_argument('-c', '--cmd', default='software', help='specify the command')
parser.add_argument('--conf', default='debug', help='specify the configuration')
args = parser.parse_args()
print(args)

os.chdir(FREEDOM_E_SDK)
cmd = 'make PROGRAM=%s TARGET=%s %s' % (args.program, args.target, args.cmd)
print(cmd)
os.system(cmd)


#/media/lingkong/Data/git/SiFive/sifive_coreip_E21_AHB_rtl_full_v19_08p2p0_release/freedom-e-sdk/software/hello/debug/hello.hex
objdump = os.getenv('RISCV_PATH') + '/bin/riscv64-unknown-elf-objdump'
print(objdump)

if args.cmd == 'software':
    elf = '%s/%s/%s/%s/%s.elf' % (FREEDOM_E_SDK, args.cmd, args.program, args.conf, args.program)
    print(elf)
    #dump_cmd = '%s -S %s > %s' % (objdump, elf, os.path.splitext(elf)[0] + '.c')
    dump_cmd = '%s -S %s > %s' % (objdump, elf, elf + '.c')
    print(dump_cmd)
    os.system(dump_cmd)
    output_path = os.path.dirname(elf)
    print('\033[1;41m%s\033[0m' % '\/' * 40)
    print(output_path)
    os.system('ls -hl %s' % output_path)
